<template>
  <div>
    <span v-if="readonly">
      <el-tag v-if="enabled" type="success">启用</el-tag>
      <el-tag v-else type="info">禁用</el-tag>
    </span>
    <el-switch
      v-else
      v-model="enabled"
      :active-color="primaryColor ? null : '#67C23A'"
      @change="onChange"
    />
  </div>
</template>

<script>
export default {
  model: {
    event: 'change'
  },
  props: {
    readonly: Boolean,
    value: null,
    admin: Object,
    primaryColor: Boolean
  },
  watch: {
    value(v) {
      this.enabled = !!v;
    }
  },
  data() {
    return {
      enabled: !!this.value
    };
  },
  methods: {
    async onChange(value) {
      const ret = await this.$http.put('/api/admin/toggleAdmin', {id: this.admin.id, status: +value});
      if (ret.success) {
        this.$message.success(`${value ? '启用' : '禁用'}成功`);
        this.admin.status = +!value;
      } else {
        this.enabled = +!value;
      }
      this.$emit('change', value);
    }
  },
}
</script>